/*
*  Copyright 2019-2023 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.information.service.impl;

import me.zhengjie.exception.BizException;
import me.zhengjie.modules.file.rest.FileController;
import me.zhengjie.modules.information.domain.Article;
import me.zhengjie.modules.information.domain.req.ArticleDeleteCmd;
import me.zhengjie.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import me.zhengjie.modules.information.service.ArticleService;
import me.zhengjie.modules.information.domain.vo.ArticleQueryCriteria;
import me.zhengjie.modules.information.mapper.ArticleMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import me.zhengjie.utils.PageUtil;

import java.time.LocalDateTime;
import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

import me.zhengjie.utils.PageResult;

/**
* @description 服务实现
* @author yiwei.he
* @date 2024-04-09
**/
@Service
@RequiredArgsConstructor
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article> implements ArticleService {

    private final ArticleMapper articleMapper;

    private final FileController fileController;


    /**
     * 查询列表不返回content，文章内容放到详情中返回（小程序查询接口）
     * @param criteria 条件
     * @param page 分页参数
     * @return
     */
    @Override
    public PageResult<Article> getArticleList(ArticleQueryCriteria criteria, Page<Object> page){
        return PageUtil.toPage(articleMapper.getArticleList(criteria, page));
    }

    /**
     *
     * @param criteria 条件参数
     * @return
     */
    @Override
    public List<Article> queryAll(ArticleQueryCriteria criteria){
        return articleMapper.findAll(criteria);
    }

    /**
     * 后管
     * @param criteria
     * @param page
     * @return
     */
    @Override
    public PageResult<Article> queryAll(ArticleQueryCriteria criteria, Page<Object> page) {
        return PageUtil.toPage(articleMapper.findAll(criteria, page));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(Article resources) {
        save(resources);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Article resources) {
        Article article = getById(resources.getId());
        // 设置修改时间
        article.setUpdateTime(LocalDateTime.now());
        article.copy(resources);
        saveOrUpdate(article);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteAll(Set<Long> ids) {
        List<Article> articleList = listByIds(ids);
        // 修改需要删除的资讯的状态
        articleList.forEach(entity -> entity.setIsDelete(1));
        updateBatchById(articleList);
    }


    @Override
    public void download(List<Article> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (Article article : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("标题", article.getTitle());
            map.put("封面", article.getCover());
            map.put("文章内容", article.getArticleContent());
            map.put("浏览量", article.getPageView());
            map.put("简介", article.getIntro());
            map.put("作者（这里应该是学校名称，哪一所院校发布的）", article.getAuthor());
            map.put("标签（预留）", article.getTag());
            map.put("文章状态【1：草稿 2：已发布 3：废弃】", article.getStatus());
            map.put("文章类别【1：公招信息  2：培训考证  3：升学择校 4：招聘信息】", article.getArticleType());
            map.put("是否删除【0：未删除 1：已删除】", article.getIsDelete());
            map.put("发布时间", article.getPublishTime());
            map.put("修改时间（仅仅记录发布后最后一次修改的时间）", article.getUpdateTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public Article getArticleDetail(ArticleQueryCriteria criteria) {
        if(criteria.getId() != null){
            // 每查看详情页面一次，浏览量 + 1
            Article article = articleMapper.selectById(criteria.getId());
            // 如果文章不为空
            if(article != null){
                article.setPageView(article.getPageView() + 1);
                articleMapper.updateById(article);
            }
        }
        return articleMapper.selectById(criteria.getId());
    }
}